package com.pnemec.net;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpConnectionParams;

import com.pnemec.util.Debug;

public class Uploader {
	public static final int NOTUSED = 1;
	public static final int FINISHED_OK = 0;
	public static final int FINISHED_ERR = 3;
	public static final int ERR = 4;
	private URL url;
	private File file;
	private int status = NOTUSED;
	private StringBuffer returnMessage = null;

	public Uploader(URL url, File file) throws FileNotFoundException {
		this.url = url;
		if (file == null) {
			Debug.log("Uplaoder called with null file");
			throw new NullPointerException("Uplaoder called with null file");
		}
		if (!file.exists()) {
			this.file = null;
			Debug.log("Uplaoder.constructor: file: " + file.toString()
					+ " do not exist");
			status = ERR;
			throw new FileNotFoundException("file " + file.toString()
					+ " can`t be found");
		}
		this.file = file;

	}

	/**
	 * do upload from FILE to URL set status
	 */
	public void doUpload() {
		// DataOutputStream out=null;
		/* int maxSizeRequest = 1024000; */
		try {
			HttpClient client = new HttpClient();
			client.setTimeout(8000);
			PostMethod filePost = new PostMethod(url.toString());
			Part[] parts = {
			/* new StringPart("MAX_FILE_SIZE",String.valueOf(maxSizeRequest)), */
			new FilePart("userfile", file) };
			filePost.setRequestEntity(new MultipartRequestEntity(parts,
					filePost.getParams()));

			int tmpStatus = client.executeMethod(filePost);
			if (tmpStatus == HttpStatus.SC_OK) {
				status = FINISHED_OK;
				Debug.log("Uploading file from: " + file.getName() + " to: "
						+ url.toString() + " finished succesfully");
			} else {
				status = FINISHED_ERR;
				Debug.log("Uploading file from: " + file.getName() + " to: "
						+ url.toString() + " didn`t finish succesfully: "
						+ tmpStatus + "(see HttpStatus.)");
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					filePost.getResponseBodyAsStream()));
			String line;
			returnMessage = new StringBuffer();
			while ((line = br.readLine()) != null) {
				returnMessage.append(line + "\n");
			}
		} catch (IOException ioe) {
			// TODO Auto-generated catch block
			ioe.printStackTrace();
		}
		System.out.println("Uploading finished");
	}

	/**
	 * return status TODO - probably not correctly thread-safe (status can be
	 * changed in doUpload method which is not synchronized)
	 * 
	 * @return
	 */
	synchronized public int getStatus() {
		return status;
	}

	synchronized public String getReturnMessage() {
		return returnMessage.toString();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Uploader init");
		// Uploader u = new Uploader("http://localhost/~pavel/__upload",
		// "/tmp/img2.img");
		// Uploader u = new Uploader("http://localhost/~thidney/__upload",
		// "/tmp/test.tar.bz2");
		// Uploader u = new
		// Uploader("http://localhost/~thidney/__upload","/tmp/test.txt");
		try {
			URL url = new URL("http://wintermute.suse.cz/~pavel/__upload");
			Uploader u = new Uploader(
					url,
					new File("/tmp/test3.png"));
			System.out.println("Uploader going to do the download");
			u.doUpload();
			System.out.println("Status: " + u.getStatus());
			System.out.println("Message: " + u.getReturnMessage());
		} catch (FileNotFoundException fnfe) {
			System.out.println("Check test case, wrong file or url");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
